import { _decorator, Component, screen, Node, find, Widget } from 'cc';
import AbstractComponent from '../base/AbstractComponent';
import { Label } from 'cc';
import { Button } from 'cc';
import UtilTool from '../tools/UtilTool';
import { App } from '../App';
import { tween } from 'cc';
import { UITransform } from 'cc';
import { loadCommonPreFab, showErrorTip, showTip } from '../tools/PopuUp';
import { Sprite } from 'cc';
import { PD } from '../player/PlayerData';
import wsTool from '../net/ws';
import CommConst from '../const/CommConst';
import { Reward } from './Reward';
import { view } from 'cc';
const { ccclass, property } = _decorator;

// let ITEM_LIST = [
//     1, 3, 5, 10, 20, 30, 50, 100, 200, 500, 1000, 2000
// ]

@ccclass('InvitePanel')
export class InvitePanel extends AbstractComponent {
    
    @property(Label)
    label_link : Label = null; // 邀请链接

    @property(Label)
    label_play_count : Label = null; // 每次消耗门票数量

    @property(Label)
    label_invite_count : Label = null; // 邀请人数

    @property(Label)
    label_ticket : Label = null; // 门票数量

    @property(Node)
    node_text_list : Node = null; // 奖品列表文本

    @property(Button)
    btn_play : Button = null; // 转盘按钮

    @property(Node)
    node_wheel : Node = null; // 转盘节点

    @property(Sprite)
    sp_wheel : Sprite = null; // 转盘图片

    linkStr : string = "" // 邀请链接

    onLoad() {
        const winAspectRatio = screen.windowSize.height / screen.windowSize.width;
        // 这种情况是手机高度很小的时候(特殊处理)
        if (winAspectRatio<=1.7) {
            find("contentNode/node_invite",this.node).setScale(0.01,0.01,0.01)
            setTimeout(() => {
                let vs = view.getVisibleSize()
                find("contentNode/node_invite",this.node).setScale(1,1,1)
                find("contentNode/node_invite",this.node).setPosition(0, vs.height/2-270)
            }, 100)
        }
    }

    start() {
        this.node_text_list.children.forEach((node, index) => {
            node.getComponent(Label).string = ""
        })

        this.label_play_count.string = ""
        this.label_invite_count.string = ""
        this.label_ticket.string = ""

        
        let hostName = window.location.hostname
        if(hostName.indexOf("http") == -1) {
            hostName = "http://" + hostName // 需要添加http前缀，才能在DAPP软件上运行
        }
        
        // 邀请链接
        this.linkStr = hostName + "?invite=" + PD.playerInfo.userId
        this.label_link.string = UtilTool.getIngoreText(this.linkStr + "abcdef", 26)
        
        // 获取邀请数据
        wsTool.send({msgCode:CommConst.Req_INVITE_DATA})
        .then((data) => {
            // UtilTool.printLog("test invite", data)
            this.initData(data)
        })

        this.updateHead()

    }

    // 更新头像
    updateHead() {
        let headDict = App.Scene.getHallRes("images/head")
        if (headDict["head_" + PD.user.headId]) {
            find("contentNode/node_invite/bg_head",this.node).getComponent(Sprite).spriteFrame = headDict["head_" + PD.user.headId]
        }
    }

    // 初始化界面数据
    initData(data) {

        // data = {
        //     inviterNum : 1, // 邀请人数
        //     rewardList : [500, 1000], // 12的奖品列表，需要后台动态配置
        //     ticket : 2, // 门票数量
        //     onceTicket : 10, // 每次消耗门票数量
        // }

        this.label_invite_count.string = UtilTool.formatStr(App.language.getLanguageLab(2040), data.inviterNum) // 邀请人数
        this.label_ticket.string = data.ticket // 门票数量
        this.label_play_count.string = UtilTool.formatStr(App.language.getLanguageLab(2046), data.onceTicket) // 每次消耗门票数量

        // 12的奖品列表，需要后台动态配置
        data.rewardList.forEach((item) => {
            let index = item.id - 1
            let text = this.node_text_list.children[index].getComponent(Label)
            text.string = UtilTool.formatStr("%s\nUSDT", item.reward)
        })

    }

    // 中奖记录按钮
    async onBtnRecord() {
        UtilTool.printLog("onBtnRecord")
        this.playClickAudio()
        await loadCommonPreFab('prefabs/hall/lotteryRecord',this.node)
    }

    // 复制
    onBtnCopy() {
        UtilTool.printLog("onBtnCopy")
        this.playClickAudio()
        UtilTool.copyText(this.linkStr, (resoult)=>{
            if (resoult){
                showTip(App.language.getLanguageLab(161))
            }
        })
    }

    // 点击转盘 
    onBtnPlay() {

        this.playClickAudio()

        wsTool.send({msgCode:CommConst.Req_LOTTERY})
        .then((data) => {
            UtilTool.printLog("test Req_LOTTERY", data)

            if(data.result == 0) {
                let rewardResult = data.lotteryResp
                let awardIndex = rewardResult.id - 1
                this.runWheel(awardIndex, rewardResult.reward)
                this.label_ticket.string = data.ticket
            } else {
                showErrorTip(data.result)
            }

        })

    }

    /** 转动轮盘
     * 
     * @param awardIndex 奖品索引, 0-11
     * @param reward 中奖金额
     */
    runWheel(awardIndex, reward) {

        UtilTool.printLog("test awardIndex", awardIndex)

        let rotate = 360 * 5 + Math.random() * 360 // 随机一个旋转角度
        let time = 3 // 旋转时间

        // 补回指针和轮盘的差值
        let angle1 = this.sp_wheel.node.angle % 360
        let angle2 = this.btn_play.node.angle % 360
        let offest = angle2 - angle1

        let rotate2 = rotate - awardIndex * 30 // 差的奖品索引个数
        rotate2 = rotate2 - offest - 15 // 15是指针和轮盘一开始的默认差值

        tween(this.sp_wheel.node).by(time, {angle : rotate}, {easing:"quadInOut"}).start()
        tween(this.btn_play.node).by(time+0.5, {angle : rotate2}, {easing:"sineInOut"}).call(()=>{
            this.showReward(reward)
        }).start()

    }

    // 显示中奖界面
    async showReward(usdtNumber) {
        let node = await loadCommonPreFab('prefabs/hall/reward',this.node)
        node.getComponent(Reward).initData(usdtNumber)
    }

    // 点击帮助
    async onBtnHelp() {
        this.playClickAudio()
        await loadCommonPreFab('prefabs/hall/inviteDescWnd',this.node)
    }

}   

